/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.event.ShopApplyEvent;
import com.yami.shop.bean.model.ShopBankCard;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.ShopBankCardMapper;
import com.yami.shop.service.ShopBankCardService;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 商家钱包信息
 *
 * @author YXF
 *  * @date 2020-04-07 14:22:08
 */
@Service
@AllArgsConstructor
public class ShopBankCardServiceImpl extends ServiceImpl<ShopBankCardMapper, ShopBankCard> implements ShopBankCardService {
    private final ShopBankCardMapper shopBankCardMapping;
    private final ApplicationContext applicationContext;
    private final Integer NOT_DEFAULT = 0;
    private final Integer DEFAULT = 1;

    @Override
    public Long insertSelective(ShopBankCard shopBankCard) {
        //银行卡卡号重复判断
        int cardCount = shopBankCardMapping.selectCount(new LambdaQueryWrapper<ShopBankCard>()
                .eq(ShopBankCard::getCardNo,shopBankCard.getCardNo())
                .eq(ShopBankCard::getShopId,shopBankCard.getShopId())
                .eq(ShopBankCard::getStatus, StatusEnum.ENABLE.value()));

        if (cardCount > 0) {
            throw new YamiShopBindException("yami.shop.card.is.exist");
        }
        int count = shopBankCardMapping.selectCount(new LambdaQueryWrapper<ShopBankCard>()
                .eq(ShopBankCard::getShopId, shopBankCard.getShopId())
                .eq(ShopBankCard::getStatus, 1)
        );
        if (count == 0){
            shopBankCard.setIsDefault(DEFAULT);
        }else {
            shopBankCard.setIsDefault(NOT_DEFAULT);
        }
        shopBankCardMapping.insertSelective(shopBankCard);
        return shopBankCard.getShopBankCardId();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBatchAndSubmitApply(List<ShopBankCard> shopBankCards, Long shopId, Long employeeId) {
        if (CollUtil.isEmpty(shopBankCards)) {
            throw new YamiShopBindException("yami.shop.bank.card.not.empty");
        }
        // 先删除已保存的银行卡信息
        shopBankCardMapping.delete(Wrappers.lambdaQuery(ShopBankCard.class).eq(ShopBankCard::getShopId, shopId));
        // 先检查银行卡信息
        this.checkSaveBankCardList(new ArrayList<>(), shopBankCards, shopId);
        // 保存银行卡信息
        shopBankCardMapping.insertBatch(shopBankCards, shopId);
        // 提交开店申请
        applicationContext.publishEvent(new ShopApplyEvent(shopId, employeeId));
    }

    @Override
    public void saveBatchByShopId(List<ShopBankCard> shopBankCardList, Long shopId) {
        if (CollUtil.isEmpty(shopBankCardList)) {
            return;
        }
        List<ShopBankCard> shopBankCards = shopBankCardMapping.selectList(Wrappers.lambdaQuery(ShopBankCard.class).eq(ShopBankCard::getShopId, shopId));
        if (CollUtil.isEmpty(shopBankCards)) {
            shopBankCards = new ArrayList<>();
        }
        // 检查银行卡信息
        this.checkSaveBankCardList(shopBankCards, shopBankCardList, shopId);
        shopBankCardMapping.insertBatch(shopBankCardList, shopId);
    }

    @Override
    public void setNotDefault(Long shopBankCardId, Long shopId) {
        shopBankCardMapping.setNotDefault(shopBankCardId, shopId);
    }

    @Override
    public void updateByShopId(ShopBankCard shopBankCard, Long shopId) {
        if (Objects.isNull(shopBankCard.getShopBankCardId())) {
            throw new YamiShopBindException("银行卡id不能为空");
        }
        int count = shopBankCardMapping.selectCount(Wrappers.lambdaQuery(ShopBankCard.class)
                .eq(ShopBankCard::getShopId, shopId)
                .eq(ShopBankCard::getCardNo, shopBankCard.getCardNo())
                .ne(ShopBankCard::getShopBankCardId, shopBankCard.getShopBankCardId())
        );
        if (count > 0) {
            throw new YamiShopBindException("yami.shop.bank.card.no.repeat");
        }
        shopBankCardMapping.updateById(shopBankCard);
    }

    @Override
    public void setDefault(Long shopBankCardId, Long shopId) {
        shopBankCardMapping.setDefault(shopBankCardId, shopId);
    }

    /**
     * 检查银行卡列表信息
     * @param savedBankCardList 已保存的银行卡列表
     * @param newBankCardList 新增的银行卡列表
     * @param shopId 用于保存银行卡的店铺id
     */
    private void checkSaveBankCardList(List<ShopBankCard> savedBankCardList, List<ShopBankCard> newBankCardList, Long shopId) {
        if (savedBankCardList.size() + newBankCardList.size() > Constant.SHOP_BANK_CARD_LIMIT_NUM) {
            throw new YamiShopBindException("银行卡数量不能超过" + Constant.SHOP_BANK_CARD_LIMIT_NUM);
        }
        Map<String, Integer> bankCardMap = new HashMap<>(5);
        savedBankCardList.forEach(item -> {
            if (bankCardMap.containsKey(item.getCardNo())) {
                throw new YamiShopBindException("已添加的银行卡中存在重复账号" + item.getCardNo() + "，请先删除重复的银行卡账号");
            }
            bankCardMap.put(item.getCardNo(), 1);
        });
        newBankCardList.forEach(item -> {
            if (bankCardMap.containsKey(item.getCardNo())) {
                throw new YamiShopBindException("银行卡账号" + item.getCardNo() + "重复");
            }
            item.setIsDefault(Objects.isNull(item.getIsDefault()) ? 0 : item.getIsDefault());
            bankCardMap.put(item.getCardNo(), 1);
        });
    }

}
